package org.nokatag.tagjava;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

import org.nokatag.system.DBCon;

/**
 * 显示某一数据表
 * @author rebin
 *
 */
public class DBDataRow extends NokaTag {

	private static final long serialVersionUID = 3208038120670057441L;
	
	private String sql = null;//查询sql
	private String val = null;//变量名字
	
	public int doStartTag()throws JspException{
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		Connection con = DBCon.getCon();
		PreparedStatement pa = null;
		ResultSet rs = null;
		Map<String,Object> rowMap = new HashMap<String,Object>();
		try{
			if(null!=con){
				pa = con.prepareStatement(sql);
			}
			if(null!=pa){
				rs = pa.executeQuery();
			}
			if(null!=rs){
				ResultSetMetaData rsmd = rs.getMetaData();
				int columnCount = rsmd.getColumnCount();
				if(rs.next()){
			    	for(int i=1;i<=columnCount;i++){
			    		rowMap.put(rsmd.getColumnName(i).toLowerCase(), rs.getObject(i));
			    	}
				}
			}
		}catch(Exception se){
			se.printStackTrace();
		}finally{
			try{
				if(rs!=null)
					rs.close();
			}catch(Exception se){}
			try{
				if(pa!=null)
					pa.close();
			}catch(Exception se){}
		}
		request.setAttribute(val,rowMap);
		return EVAL_BODY_INCLUDE;
	}

	public String getSql() {
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public String getVal() {
		return val;
	}

	public void setVal(String val) {
		this.val = val;
	}
}